# apps/your_app/your_module/api/item_update.py
import frappe
from frappe import _

@frappe.whitelist(allow_guest=False)
def save_ai_parsed_item_fields_batch():
    """
    批量保存 AI 解析后的物料自定义字段数据
    """
    import json
    # 从请求中解析 JSON 数据
    try:
        data = frappe.request.get_json()
    except Exception:
        frappe.throw(_("Invalid or missing JSON body"))

    # 1. 字段映射（英文字段名 → ERPNext 的字段名）
    field_map = {
        "surface_area": "custom_表面积",
        "type": "custom_type",
        "volume": "custom_volume",
        "height": "custom_height",
        "surface_area_to_volume_ratio": "custom_surface_area_to_volume_ratio",
        "vertical_face_ratio": "custom_vertical_face_ratio",
        "length": "custom_length",
        "width": "custom_width",
        "average_curvature": "custom_average_curvature",
        "model_complexity": "custom_model_complexity",
        "max_dimension": "custom_max_dimension",
        "rod_diameter": "custom_rod_diameter"
    }

    items = data.get("items")
    if not items or not isinstance(items, list):
        frappe.throw(_("Missing or invalid 'items' list"))

    results = []

    for entry in items:
        item_code = entry.get("item_code")
        if not item_code:
            results.append({"item_code": None, "status": "failed", "message": "Missing item_code"})
            continue

        try:
            item = frappe.get_doc("Item", item_code)
            updated_fields = []

            for en_field, erp_field in field_map.items():
                if en_field in entry:
                    setattr(item, erp_field, entry[en_field])
                    updated_fields.append(en_field)
                    
            if item.custom_表面积 and str(item.custom_表面积).strip() not in ("", "0", "0.0"):
                item.custom_是否建模 = 1
            item.save()
            results.append({
                "item_code": item_code,
                "status": "success",
                "updated_fields": updated_fields
            })
        except Exception as e:
            results.append({
                "item_code": item_code,
                "status": "failed",
                "message": str(e)
            })

    frappe.db.commit()

    return {
        "status": "completed",
        "results": results
    }